using BarManager.Core.ApplicationService.Interfaces;
using BarManager.Core.Entity;
using BarManager.UI.Web.HtmlHelpers;
using BarManager.UI.Web.Models;
using System.Linq;
using System.Web.Mvc;

namespace BarManager.UI.Web.Controllers
{
    [Authorize(Users = "admin")]
    public class EmpleadoController : BaseController<EmpleadoViewModel, Empleado, int>
    {
        private ICargoService CargoService { get; set; }

        public EmpleadoController(IEmpleadoService service, ICargoService cargoService)
            : base(service)
        {
            CargoService = cargoService;
        }

        public override ActionResult Index(int id = 0)
        {
            //- Cargamos el listado de Cargos
            EmpleadoViewModel model = new EmpleadoViewModel { Cargos = CargoService.GetAll().OrderBy(x => x.Descripcion) };

            //- Cargamos el empleado a editar
            if (id > 0) model.Entity = Service.Get(x => x.Id == id);

            return View(model);
        }

        public override ActionResult List(string filter, int page = 1)
        {
            EmpleadoViewModel model = new EmpleadoViewModel
            {
                Entities = this.Service.Find(x =>
                                        (filter == null || x.Nombre.Contains(filter)
                                            || x.Apellido.Contains(filter)
                                            || x.Cargo.Descripcion.Contains(filter)
                                        ) && x.FechaBaja == null)
                                        .Skip((page - 1) * PageSize)
                                        .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = this.Service.Find(x =>
                                        (filter == null || x.Nombre.Contains(filter)
                                            || x.Apellido.Contains(filter)
                                            || x.Cargo.Descripcion.Contains(filter)
                                        ) && x.FechaBaja == null).Count()
                }
            };
            model.Filter = filter;     
            return View(model);
        }

        public override ActionResult Save(EmpleadoViewModel model)
        {
            //- Cargamos combo de zonas
            if (model.Cargos == null) model.Cargos = CargoService.GetAll().OrderBy(x => x.Descripcion);

            //- Guardamos o actualizamos
            if (model.Entity.Id > 0)
                ErrorList = this.Service.Update(model.Entity);
            else
                ErrorList = this.Service.Add(model.Entity);

            return ShowError(model, ErrorList);
        }              
    }
}
